//
//  BGAddInviteOneTableViewController.m
//  bigMall
//
//  Created by LTOVE on 16/8/23.
//  Copyright © 2016年 thinklev. All rights reserved.
//

#import "BGAddInviteOneTableViewController.h"
#import "BGGoodAttrsModel.h"
#import "BGAddInviteOneTableViewCell.h"
#import "BGAddInviteOneBaseModel.h"

#import "BGAddInviteOneTextFildCellModel.h"
#import "BGAddInviteOnePickViewModel.h"
#import "BGAddInviteOneTextAreaModel.h"
#import "BGAddInviteOneTitleModel.h"
#import "BGInitArea.h"
#import "BGAddInviteOneBaseModel.h"
#import "BGDateResult.h"
#import "BGFenLeiModel.h"
#import "BGTwoLevelDataModel.h"
#import "BGAddInviteOneFenQiKuanModel.h"
#import "BGSmallNumModel.h"
#import "BGAddInviteOneStepParam.h"
#import "BGCalculateMarginModel.h"
#import "BGCalculateCreditModel.h"
#import "BGAddInviteOneModel.h"
#import "MJExtension.h"
#import "BGAddInfoPageController.h"
//#define changedStrs self.paramModel.leastNumber = model.changedStr;
#import "BGGoodInfoDataResult.h"
#import "BGGoodInfoResult.h"

#import "MBProgressHUD.h"
#import "MBProgressHUD+MJ.h"

@interface BGAddInviteOneTableViewController ()<BGAddInviteOneTableViewCellDeleGate>{

    NSMutableArray *_dataArray;
//    UIGestureRecognizer *_gest;
    NSMutableArray *_fenLeiIdArray;
//    NSMutableArray *_tempArray;
    BOOL _guaDanFS;
    BOOL _isClickGuaDanFangShi;
    NSString *cat_id;
    NSArray *goodsAttrArray;
    CGFloat _y;
}

@property (nonatomic,strong)BGAddInviteOneStepParam *paramModel;

@end

@implementation BGAddInviteOneTableViewController

- (BGAddInviteOneStepParam *)paramModel
{
    if (!_paramModel) {
        _paramModel = [[BGAddInviteOneStepParam alloc]init];
    }
    return _paramModel;
    
}
- (void)viewWillDisappear:(BOOL)animated
{
    NSArray *controls = self.navigationController.viewControllers;
    if (controls.count > 1 && [controls objectAtIndex:controls.count -2] == self) {
        for (UIView *view in self.tableView.subviews) {
            view.userInteractionEnabled = NO;
        }
    }
}
//- (void)viewWillAppear:(BOOL)animated
//{
//
//}

- (void)viewDidLoad {
    [super viewDidLoad];
    //    [self.tableView reloadData];
    self.tableView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyBoardShowNotify:) name:UIKeyboardDidShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyBoardCloseNotify) name:UIKeyboardDidHideNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyBoardShowNotifys:) name:UIKeyboardWillChangeFrameNotification object:nil];
//    self.isYetDada = YES;
    if (!self.isYetDada) {
        [self initDateWithModel:nil];
    }
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    GWLog(@"sss");
}
- (void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    GWLog(@"sssssss");
}
/**
 *  下一步  跳转下一个控制器
 */
- (void)nextStepClick
{
    NSLog(@"dianjile");
    
    //###############
//    BGAddInfoPageController *vc = [[BGAddInfoPageController alloc]init];
//    UIBarButtonItem *bacItem = [[UIBarButtonItem alloc]init];
//    [bacItem setTitle:@""];
//    vc.title = @"附加信息";
//    self.navigationItem.backBarButtonItem = bacItem;
    
    
//    [self.navigationController pushViewController:vc animated:YES];
//##########
    if (self.isYetDada) {
        BGAddInfoPageController *vc = [[BGAddInfoPageController alloc]init];
        UIBarButtonItem *bacItem = [[UIBarButtonItem alloc]init];
        [bacItem setTitle:@""];
        vc.title = @"附加信息";
        vc.catId = cat_id;
        if ([self.status isEqualToString:@"-1"] || [self.status isEqualToString:@"2"]) {
            vc.status = YES;
        }else{
            vc.status = NO;
        }
        
        //            GWLog(@"--------%@",model.invite_id);
        vc.invite_id = self.goodsId;
        vc.attrArray = goodsAttrArray;
        self.navigationItem.backBarButtonItem = bacItem;
        
        
        [self.navigationController pushViewController:vc animated:YES];
    }else{
    
    UIAlertController *alertVc = [UIAlertController alertControllerWithTitle:@"提示" message:@"请输入支付密码" preferredStyle:UIAlertControllerStyleAlert];
    [alertVc addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
        
        textField.placeholder = @"支付密码";
        textField.secureTextEntry = YES;
    }];
    UIAlertAction *sure = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        UITextField *textFild = [alertVc.textFields firstObject];
        self.paramModel.payPassword = textFild.text;
        
        
        NSDictionary *dic = [self.paramModel getParamDic];
        NSLog(@"%@",dic);
        [BGDateResult addInviteOneWithParam:dic success:^(NSObject *result) {
            
            BGAddInviteOneModel *model = (BGAddInviteOneModel *)result;
            //        [self alertMessageBoxWithMessage:model.msg];
            
            //弹窗
            UIAlertController *alertVc = [UIAlertController alertControllerWithTitle:@"提示" message:model.msg preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *sure = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                
                if ([model.status isEqualToString:@"1"]) {
                    BGAddInfoPageController *vc = [[BGAddInfoPageController alloc]init];
                    UIBarButtonItem *bacItem = [[UIBarButtonItem alloc]init];
                    [bacItem setTitle:@""];
                    vc.title = @"附加信息";
                    vc.status = YES;
                    vc.catId = self.paramModel.catId;
                    //            GWLog(@"--------%@",model.invite_id);
                    vc.invite_id = model.invite_id;
                    self.navigationItem.backBarButtonItem = bacItem;
                    
                    
                    [self.navigationController pushViewController:vc animated:YES];
                }
                //            GWLog(@"%@",model.msg);
                
            }];
            
            [alertVc addAction:sure];
            [self presentViewController:alertVc animated:YES completion:^{
                
                
            }];
            
        } failure:^(NSError *error) {
            
        }];
        
        
    }];
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
        
    }];
    [alertVc addAction:sure];
    [alertVc addAction:cancel];
    [self presentViewController:alertVc animated:YES completion:^{
        
        
    }];
    
    
    
    
    }

    
}



- (void)setParamModelValueWith:(BGAddInviteOneBaseModel *)model
{
    switch (model.paramType) {
        case BGAddInviteOneParamTypeCatId:
//            self.paramModel.catId = [model.indexArray lastObject];
            {
                NSArray *arr = model.indexArray;
                if (model.indexArray.count == 3) {
                    
                    NSInteger one = [model.indexArray[0] integerValue];
                    NSInteger two = [model.indexArray[1] integerValue];
                    NSInteger three = [model.indexArray[2] integerValue];
//                    NSArray *oneArray = _fenLeiIdArray[one];
//                    NSArray *twoArray = oneArray[two];
//                    NSString *catid = twoArray[three];
                    self.paramModel.catId = _fenLeiIdArray[one][two][three];
                }
                NSLog(@"%@",arr);
//                NSLog(@"%@",)
            }
//            NSLog(@"%@",model.indexArray);
            if (_fenLeiIdArray.count != 0) {
                NSLog(@"%@",_fenLeiIdArray);
            }
            
            break;
        case BGAddInviteOneParamTypeTitle:
            self.paramModel.title = model.changedStr;
            break;
        case BGAddInviteOneParamTypeProductCode:
            self.paramModel.productCode = model.changedStr;
            break;
        case BGAddInviteOneParamTypeIsPorted:
            if ([[model.indexArray firstObject] isEqualToString:@"0"]) {
                self.paramModel.isPorted = @"1";
                self.paramModel.leastNumber = nil;
            }else{
                self.paramModel.isPorted = @"0";
                self.paramModel.leastNumber = @"0";
            }
            break;
        case BGAddInviteOneParamTypeLeastNumber:
            self.paramModel.leastNumber = model.changedStr;
            break;
        case BGAddInviteOneParamTypePrice:
            self.paramModel.price = model.changedStr;
            if (self.paramModel.number) {
                CGFloat price = [self.paramModel.price floatValue];
                CGFloat Number = [self.paramModel.number floatValue];
                self.paramModel.totalPrice = [NSString stringWithFormat:@"%lf",price * Number];
                [self loadGuaDanFangShi];
            }
            break;
        case BGAddInviteOneParamTypeTotalPrice:
#warning 计算总价
            break;
        case BGAddInviteOneParamTypeBuyMargin:
 #warning 计算总价
            break;
        case BGAddInviteOneParamTypeCreditNum:
#warning 没做
            break;
        case BGAddInviteOneParamTypePayType:
        { NSString *payType = [model.indexArray firstObject];
            payType = [NSString stringWithFormat:@"%d",([payType intValue] + 1)];
            self.paramModel.payType = payType;
            switch ([payType intValue]) {
                case 1:
                    //全款
                    self.paramModel.payScale = @"100,0,0";
                    break;
                case 2:
                    //分期款
//                    在这没法填
                    self.paramModel.payScale = nil;
                    break;
                case 3:
                    //货到付款款
                    self.paramModel.payScale = @"0,0,100";
                    break;
                default:
                    break;
            }
        }
            
            break;
        case BGAddInviteOneParamTypePublishType:
        { NSString *payType = [model.indexArray firstObject];
            payType = [NSString stringWithFormat:@"%d",([payType intValue] + 2)];
            self.paramModel.publishType = payType;
        }
            break;
        case BGAddInviteOneParamTypePayScale:
            //付款百分比
            break;
        case BGAddInviteOneParamTypeMarginScale:
            self.paramModel.marginScale = model.changedStr;
            break;
        case BGAddInviteOneParamTypeDeliveryType:
        { NSString *payType = [model.indexArray firstObject];
            payType = [NSString stringWithFormat:@"%d",([payType intValue] + 1)];
            self.paramModel.deliveryType = payType;
        }
            break;
        case BGAddInviteOneParamTypeDeliveryArea:
            self.paramModel.province = model.addrIdStrArray[0];
            self.paramModel.city = model.addrIdStrArray[1];
            self.paramModel.county = model.addrIdStrArray[2];
            self.paramModel.deliveryArea = model.changedStr;
            break;
        case BGAddInviteOneParamTypeProvince:
            
            break;
        case BGAddInviteOneParamTypeCity://征用过来的  当做分期款
        {
            if (model.firstMoney.length == 0 || model.SecMoney.length == 0 || model.LastMoney.length == 0) {
                break;
            }
            CGFloat oneValue = [model.firstMoney floatValue];
            CGFloat twoValue = [model.SecMoney floatValue];
            CGFloat threeValue = [model.LastMoney floatValue];
            if ((oneValue + twoValue + threeValue) != 100) {
                [self alertMessageBoxWithMessage:@"定金、中期款、尾款比例和不为100"];
            }else{
                self.paramModel.payScale = [NSString stringWithFormat:@"%.2f,%.2f,%.2f",oneValue,twoValue,threeValue];
            }
        }
            break;
        case BGAddInviteOneParamTypeCounty:
            
            break;
        case BGAddInviteOneParamTypeStartTime:
            self.paramModel.startTime = model.timeStr;
            break;
        case BGAddInviteOneParamTypeEndTime:
            self.paramModel.endTime = model.timeStr;
            break;
        case BGAddInviteOneParamTypeRemark:
            self.paramModel.remark = model.changedStr;
            break;
        case BGAddInviteOneParamTypeNumber:
            self.paramModel.number = model.changedStr;
            if (self.paramModel.price) {
                CGFloat price = [self.paramModel.price floatValue];
                CGFloat Number = [self.paramModel.number floatValue];
                self.paramModel.totalPrice = [NSString stringWithFormat:@"%lf",price * Number];
                [self loadGuaDanFangShi];
            }
            break;
        default:
            break;
    }
}

- (void)alertMessageBoxWithMessage:(NSString *)message
{
    UIAlertController *alertVc = [UIAlertController alertControllerWithTitle:@"提示" message:message preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
        
    }];
    [alertVc addAction:cancel];
    [self presentViewController:alertVc animated:YES completion:^{
        
        
    }];
}


#pragma mark - ⬇️cell 值改变

/**
 *  cell值改变的代理
 *
 *  @param model model description
 */
- (void)cellModelChangedWithModel:(BGAddInviteOneBaseModel *)model
{
    NSMutableArray *tempArray = _dataArray[model.indexPath.section];
//    _tempArray = tempArray;
    [tempArray replaceObjectAtIndex:model.indexPath.row withObject:model];
    [_dataArray replaceObjectAtIndex:model.indexPath.section withObject:tempArray];
//    [self.tableView reloadRowsAtIndexPaths:@[model.indexPath] withRowAnimation:UITableViewRowAnimationLeft];
    NSString *title = [model.title substringToIndex:2];
    if ([title isEqualToString:@"支付"]) {
        if (!(model.indexArray.count == 0)) {
//            NSLog(@"进来了%@",model.indexArray);
            if ([[model.indexArray firstObject] isEqualToString:@"1"]) {
//                分期付款
                switch (tempArray.count) {
                    case 3:
                        //替换
                        
                        break;
                        
                    default:
                        //插入
                    {
                        BGAddInviteOneFenQiKuanModel *fenQiModel = [[BGAddInviteOneFenQiKuanModel alloc]init];
                        fenQiModel.paramType = BGAddInviteOneParamTypeCity;
                        [tempArray insertObject:fenQiModel atIndex:1];
//                        NSLog(@"%@",tempArray);
                        [_dataArray replaceObjectAtIndex:model.indexPath.section withObject:tempArray];
                       
//                        [self.tableView reloadData];
                    }
                        break;
                }
            }else{
            
//                不是分期付款
                switch (tempArray.count) {
                    case 3:
                        //删除第二个
                        [tempArray removeObjectAtIndex:1];
                        [_dataArray replaceObjectAtIndex:model.indexPath.section withObject:tempArray];
                        model.firstMoney = @"";
                        model.SecMoney = @"";
                        model.LastMoney = @"";
                        
//                        [self.tableView reloadData];
                        break;
                        
                    default:
                        //插入{
                   
                        break;
                }
            }
            
        }
        
        
        
    }else if ([title isEqualToString:@"是否"]){
    // s是否拆分
        if (model.indexArray.count == 0) {
            return;
        }
        NSMutableArray *tempsArray = _dataArray[1];
        if ([[model.indexArray firstObject] isEqualToString:@"0"]) {
            //拆分订单
            switch (tempsArray.count) {
                case 3:
                    //替换
                    
                    break;
                    
                default:
                    //插入
                {
                    BGAddInviteOneTextFildCellModel *fenQiModel = [[BGAddInviteOneTextFildCellModel alloc]init];
                    fenQiModel.paramType = BGAddInviteOneParamTypeLeastNumber;
                    fenQiModel.title = @"最小供应量:";
                    
                    [tempsArray insertObject:fenQiModel atIndex:2];
                    //                        NSLog(@"%@",tempArray);
                    [_dataArray replaceObjectAtIndex:1 withObject:tempsArray];
                    
                    //                        [self.tableView reloadData];
                }
                    break;
            }
        }else{
        //不拆分订单
            switch (tempsArray.count) {
                case 3:
                    //删除第二个
                {
//                    NSMutableArray *tempsArray = _dataArray[1];
                    [tempsArray removeObjectAtIndex:2];
                    [_dataArray replaceObjectAtIndex:1 withObject:tempsArray];
                }
                    //                        [self.tableView reloadData];
                    break;
                    
                default:
                    //插入{
                    
                    break;
            }

        }
    }else if ([title isEqualToString:@"挂单"]){
        //设置挂单方式
        if (model.indexArray.count == 0) {
            return;
        }
        
        
        if ([[model.indexArray firstObject] isEqualToString:@"0"]) {
            //保证金挂单
            
            
            _guaDanFS = YES;
            _isClickGuaDanFangShi = YES;
            [self loadGuaDanFangShi];
            
            
        }else{
            //信誉挂单
            
            
            _guaDanFS = NO;
            _isClickGuaDanFangShi = YES;
            [self loadGuaDanFangShi];
        }
    }
    
    
    [self.tableView reloadData];
//    NSLog(@"%@",[model class]);
//     NSLog(@"%@",_dataArray);
//    [self.tableView removeGestureRecognizer:_gest];
    [self setParamModelValueWith:model];
}

- (void)loadGuaDanFangShi
{
    NSString *str = self.paramModel.totalPrice;
    if (!_isClickGuaDanFangShi || !self.paramModel.totalPrice) {
        return;
    }
    if (_guaDanFS) {
        //保证金
        [self caculateMaginWithPrice:self.paramModel.totalPrice];
    }else{
        //信誉
        [self caculateCreatsWithPrice:self.paramModel.totalPrice];
    }
}

- (void)caculateCreatsWithPrice:(NSString *)price
{
    NSMutableArray *_tempArray = _dataArray[3];
    [BGDateResult CalculateCreditWithRole:@"buyer" type:@"invite" money:price success:^(NSObject *result) {
        BGCalculateCreditModel *model = (BGCalculateCreditModel *)result;
        BGSmallNumModel *BzjModel = [[BGSmallNumModel alloc]init];
        BzjModel.title = @"信誉值:";
        BzjModel.OnwValue = [NSString stringWithFormat:@"当前信誉值:%@",model.ownCredit];
        BzjModel.needValue = [NSString stringWithFormat:@"挂单使用信誉值:%@",model.credit];
        self.paramModel.buyMargin = @"0.00";
        CGFloat temp = [[NSString stringWithFormat:@"%@",model.credit] floatValue];
        self.paramModel.creditNum = [NSString stringWithFormat:@"%.3f",temp];
        if (_tempArray.count == 1) {
            [_tempArray addObject:BzjModel];
        }else{
            [_tempArray replaceObjectAtIndex:1 withObject:BzjModel];
        }
        [self.tableView reloadData];
    } failure:^(NSError *error) {
        
        
    }];
}

- (void)caculateMaginWithPrice:(NSString *)price
{
    NSMutableArray *_tempArray = _dataArray[3];
    [BGDateResult calculateMarginWithRole:@"buyer" type:@"invite" money:price objId:@"" success:^(NSObject *result) {
        BGCalculateMarginModel *model = (BGCalculateMarginModel *)result;
        
        BGSmallNumModel *BzjModel = [[BGSmallNumModel alloc]init];
        BzjModel.title = @"保证金:";
        BzjModel.OnwValue = [NSString stringWithFormat:@"当前可用金额:%@",model.cash];
        BzjModel.needValue = [NSString stringWithFormat:@"挂单需要冻结金额:%@",model.margin];
        self.paramModel.buyMargin = [NSString stringWithFormat:@"%@",model.margin];
        self.paramModel.creditNum = @"0.000";
        if (_tempArray.count == 1) {
            [_tempArray addObject:BzjModel];
        }else{
            [_tempArray replaceObjectAtIndex:1 withObject:BzjModel];
        }
        [self.tableView reloadData];
    } failure:^(NSError *error) {
        
        
    }];

}

- (instancetype)init
{
    if (self = [super init]) {
        
        UIBarButtonItem *RigBar = [[UIBarButtonItem alloc]initWithTitle:@"下一步" style:UIBarButtonItemStylePlain target:self action:@selector(nextStepClick)];
//        RigBar.title = @"下一步";
        self.navigationItem.rightBarButtonItem = RigBar;
        
        
    }
    return self;
}
#pragma mark - ⬇️初始化数据
/**
 *  初始化数据
 */
- (void)initDateWithModel:(BGGoodInfoResult *)model
{
    NSMutableArray *oneGroupArray = [NSMutableArray array];
    //商品名称
    BGAddInviteOneTextFildCellModel *goodNameModel = [[BGAddInviteOneTextFildCellModel alloc]init];
    goodNameModel.paramType = BGAddInviteOneParamTypeTitle;
    goodNameModel.title = @"招标名称:";
    goodNameModel.textFildStr = model.title;
    [oneGroupArray addObject:goodNameModel];
    //分类
    BGAddInviteOnePickViewModel *sortModel = [[ BGAddInviteOnePickViewModel alloc]init];
    sortModel.title = self.isYetDada ? [NSString stringWithFormat:@"分类:%@",model.cat_name] : @"分类:";
    sortModel.textFildStr = model.cat_name;
    sortModel.paramType = BGAddInviteOneParamTypeCatId;
    sortModel.dateArray = [self loadFenLei];
    [oneGroupArray addObject:sortModel];
    //是否拆分
    BGAddInviteOnePickViewModel *splitModel = [[BGAddInviteOnePickViewModel alloc]init];
    splitModel.title = self.isYetDada ? [NSString stringWithFormat:@"是否拆分订单:%@",model.is_ported_str] : @"是否拆分订单:";
    splitModel.paramType = BGAddInviteOneParamTypeIsPorted;
    splitModel.dateArray = @[@[@"是",@"否"]];
    [oneGroupArray addObject:splitModel];
    //品牌
    BGAddInviteOneTextFildCellModel *brandModel = [[BGAddInviteOneTextFildCellModel alloc]init];
    brandModel.title = @"产品品牌:";
    brandModel.textFildStr = model.product_code;
    brandModel.paramType = BGAddInviteOneParamTypeProductCode;
    [oneGroupArray addObject:brandModel];
    
    //###############
    NSMutableArray *twoGroupArray = [NSMutableArray array];
    //单价
    BGAddInviteOneTextFildCellModel *priceModel = [[BGAddInviteOneTextFildCellModel alloc]init];
    priceModel.title = @"单价(元/吨):";
    priceModel.textFildStr = model.price;
    priceModel.paramType = BGAddInviteOneParamTypePrice;
    [twoGroupArray addObject:priceModel];
    //数量
    BGAddInviteOneTextFildCellModel *numModel = [[BGAddInviteOneTextFildCellModel alloc]init];
    numModel.title = @"数量(吨):";
    numModel.textFildStr = model.origin_number;
    numModel.paramType = BGAddInviteOneParamTypeNumber;
    [twoGroupArray addObject:numModel];
    if ([model.is_ported_str isEqualToString:@"是"]) {
        BGAddInviteOneTextFildCellModel *numModels = [[BGAddInviteOneTextFildCellModel alloc]init];
        numModels.title = @"最小供应量:";
        numModels.textFildStr = model.least_number;
        numModels.paramType = BGAddInviteOneParamTypeNumber;
        [twoGroupArray addObject:numModels];
    }
    
    
    //##############
    NSMutableArray *threeGroupArray = [NSMutableArray array];
    //支付方式
    BGAddInviteOnePickViewModel *payModel = [[BGAddInviteOnePickViewModel alloc]init];
    payModel.title = self.isYetDada ? [NSString stringWithFormat:@"支付方式:%@",model.pay_type_str] : @"支付方式:";
    payModel.paramType = BGAddInviteOneParamTypePayType;
    payModel.dateArray = @[@[@"全款",@"分期",@"货到付款"]];
    [threeGroupArray addObject:payModel];
    if (self.isYetDada && [model.pay_type_str isEqualToString:@"分期付款"]) {
        BGAddInviteOneFenQiKuanModel *FenQiModel = [BGAddInviteOneFenQiKuanModel new];
        NSString *paySql = model.pay_scale;
        NSArray *array = [paySql componentsSeparatedByString:@","];
        GWLog(@"%@",array);
        FenQiModel.firstMoney = [array firstObject];
        FenQiModel.SecMoney = array[1];
        FenQiModel.LastMoney = [array lastObject];
        [threeGroupArray addObject:FenQiModel];
    }
    
    
    
//    BGAddInviteOneFenQiKuanModel *fenqiModel = [[BGAddInviteOneFenQiKuanModel alloc]init];
//    [threeGroupArray addObject:fenqiModel];
    //保证金
    BGAddInviteOneTextFildCellModel *margineModel = [[BGAddInviteOneTextFildCellModel alloc]init];
    margineModel.title = @"投标保证金(%):";
    margineModel.textFildStr = model.margin_scale;
    margineModel.paramType = BGAddInviteOneParamTypeMarginScale;
    [threeGroupArray addObject:margineModel];
    //#############
    //挂单方式
    NSMutableArray *guaDanArray = [NSMutableArray array];
    BGAddInviteOnePickViewModel *guaDanModel = [[BGAddInviteOnePickViewModel alloc]init];
    guaDanModel.title = self.isYetDada ? [NSString stringWithFormat:@"挂单方式:%@",model.publish_type_str] :@"挂单方式:";
    guaDanModel.paramType = BGAddInviteOneParamTypePublishType;
    guaDanModel.dateArray = @[@[@"保证金",@"信誉"]];
    [guaDanArray addObject:guaDanModel];
//    BGSmallNumModel *maginModelss = [BGSmallNumModel new];
//    maginModelss.title = @"挂单方式:";
//    maginModelss.OnwValue = model.buy_margin;
//    maginModelss.needValue = model.buy_margin;
//    [guaDanArray addObject:maginModelss];
    
    
    //##############
    NSMutableArray *fourGroupArray = [NSMutableArray array];
    //交割地  交割方式
    BGAddInviteOnePickViewModel *TransazioneModel = [[BGAddInviteOnePickViewModel alloc]init];
    TransazioneModel.title = self.isYetDada ? [NSString stringWithFormat:@"交割方式:%@",model.delivery_type_str] : @"交割方式:";
    TransazioneModel.paramType = BGAddInviteOneParamTypeDeliveryType;
    TransazioneModel.dateArray = @[@[@"买家自提",@"送货上门"]];
    [fourGroupArray addObject:TransazioneModel];
    //交割地
    BGAddInviteOnePickViewModel *transAddrModel = [[BGAddInviteOnePickViewModel alloc]init];
    transAddrModel.dateArray = [BGInitArea initAreaArray];
    transAddrModel.title = self.isYetDada ? [NSString stringWithFormat:@"交割地:%@",model.delivery_area] :@"交割地:";
    transAddrModel.paramType = BGAddInviteOneParamTypeDeliveryArea;
    transAddrModel.isAddrPick = YES;
//    transAddrModel.isDatePick = YES;
    [fourGroupArray addObject:transAddrModel];
    //开始日期
    BGAddInviteOnePickViewModel *transStartDateModel = [[BGAddInviteOnePickViewModel alloc]init];
    transStartDateModel.title = self.isYetDada ? [NSString stringWithFormat:@"开始日期:%@",model.start_time_format] :@"开始日期:";
    transStartDateModel.paramType = BGAddInviteOneParamTypeStartTime;
    transStartDateModel.isDatePick = YES;
    [fourGroupArray addObject:transStartDateModel];
    //结束日期
    BGAddInviteOnePickViewModel *transEndDateModel = [[BGAddInviteOnePickViewModel alloc]init];
    transEndDateModel.title = self.isYetDada ? [NSString stringWithFormat:@"结束日期:%@",model.end_time_format] :@"结束日期:";
    transEndDateModel.paramType = BGAddInviteOneParamTypeEndTime;
    transEndDateModel.isDatePick = YES;
    [fourGroupArray addObject:transEndDateModel];
    //备注
    BGAddInviteOneTextAreaModel *textAreaModel = [[BGAddInviteOneTextAreaModel alloc]init];
    textAreaModel.title = @"填写备注:";
    textAreaModel.textViewText = model.remark;
    textAreaModel.paramType = BGAddInviteOneParamTypeRemark;
    [fourGroupArray addObject:textAreaModel];
    _dataArray = [[NSMutableArray alloc]initWithObjects:oneGroupArray,twoGroupArray,threeGroupArray,guaDanArray,fourGroupArray, nil];
    if (self.isYetDada) {
        if ([model.publish_type isEqualToString:@"2"]) {
            [self caculateMaginWithPrice:model.total_price];
        }else{
            
            [self caculateCreatsWithPrice:model.total_price  ];
        }
    }
    
    [self.tableView reloadData];
}

- (NSArray *)loadFenLei
{
    NSMutableArray *DataArray = [NSMutableArray array] ;
    
    [BGDateResult loadFenLeiWithLevel:@"level" key:@"no" success:^(NSObject *result) {
        
        BGFenLeiModel *model = (BGFenLeiModel *)result;
        NSArray *resultArray = model.res;
        NSMutableArray *oneArray = [NSMutableArray array];
        NSMutableArray *twoArray = [NSMutableArray array];
        NSMutableArray *threeArray = [NSMutableArray array];
        _fenLeiIdArray = [NSMutableArray array];
        for (int i =0 ; i < resultArray.count; i ++) {
            BGTwoLevelDataModel *model = resultArray[i];
            NSArray *sec_array = model.children;
            NSMutableArray *twoArrayTwo = [NSMutableArray array];
            NSMutableArray *threeArrayThw = [NSMutableArray array];
            
            NSMutableArray *threeArrayThws = [NSMutableArray array];
//            _fenLeiIdArray = threeArrayThws;
            [oneArray addObject:model.title];
            [twoArray addObject:twoArrayTwo];
            [threeArray addObject:threeArrayThw];
            [_fenLeiIdArray addObject:threeArrayThws];
            for (int j = 0 ; j < sec_array.count; j++) {
                BGTwoLevelDataModel *Model_t = sec_array[j];
                NSArray *three_array = Model_t.children;
                NSMutableArray *threeArrayThree = [NSMutableArray array];
                NSMutableArray *threeArrayThrees = [NSMutableArray array];
                [twoArrayTwo addObject:Model_t.title];
                [threeArrayThw addObject:threeArrayThree];
                [threeArrayThws addObject:threeArrayThrees];
                for (int k = 0 ; k < three_array.count; k ++) {
                    BGTwoLevelDataModel *model_three = three_array[k];
                    [threeArrayThree addObject:model_three.title];
                    [threeArrayThrees addObject:model_three.catId];
                    
                }
            }
        }
        [DataArray addObject:oneArray];
        [DataArray addObject:twoArray];
        [DataArray addObject:threeArray];
    } failure:^(NSError *error) {
        
        
    }];
    
    return DataArray;
}








- (void)keyBoardCloseNotify
{
//    [self.tableView removeGestureRecognizer:_gest];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
#warning Incomplete implementation, return the number of sections
    return _dataArray.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
#warning Incomplete implementation, return the number of rows
    NSMutableArray *array = _dataArray[section];
    return array.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    BGAddInviteOneBaseModel *model = _dataArray[indexPath.section][indexPath.row];
    if ([model isKindOfClass:[BGAddInviteOneTextAreaModel class]]) {
        return 80;
    }else if (indexPath.section == 3 && indexPath.row == 1){
        return 88;
    }else{
        return 44;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 20;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *headView = [UIView new];
    headView.height = 20;
    headView.width = screenW;
    headView.backgroundColor = lightGray_;
    return headView;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    BGAddInviteOneTableViewCell *cell = [BGAddInviteOneTableViewCell cellWithTableView:tableView];
    BGAddInviteOneBaseModel *model = _dataArray[indexPath.section][indexPath.row];
//    model.changedStr = @"111";
//    model.textFildStr = @"222";
//    model.timeStr = @"3333";
    model.indexPath = indexPath;
    cell.model = model;
    
    cell.userInteractionEnabled = !self.isYetDada;
    // Configure the cell...
    cell.delegate = self;
    return cell;
}
#pragma mark -- 偏移
- (void)keyBoardShowNotifys:(NSNotification *)aNotification
{
    NSDictionary *info = [aNotification userInfo];
    CGFloat duration = [[info objectForKey:UIKeyboardAnimationDurationUserInfoKey] floatValue];
    CGRect beginKeyboardRect = [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue];
    CGRect endKeyboardRect = [[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
    
    CGFloat yOffset = endKeyboardRect.origin.y - beginKeyboardRect.origin.y;
    
    GWLog(@"%f",yOffset);
//    CGRect inputFieldRect = self.inputTextField.frame;
//    CGRect moreBtnRect = self.moreInputTypeBtn.frame;
//    
//    inputFieldRect.origin.y += yOffset;
//    moreBtnRect.origin.y += yOffset;
//
    CGFloat  _kH =  yOffset;
    
    //改变textView的frame
    //    self.textView.frame = CGRectMake(0, screenH - _kH - 40, screenW, 40);
    
    //计算偏移量，20是状态栏高度，y其实就是cell底部到textView的y坐标的距离
    NSInteger y = ( _y + 20) - (screenH - (_kH + 40));

//    if (_y - yOffset - screenH > 0) {
////        <#statements#>
////    }
//    if (y > 0) {
//        [UIView animateWithDuration:duration animations:^{
//            //        self.inputTextField.frame = inputFieldRect;
//            //        self.moreInputTypeBtn.frame = moreBtnRect;
//            [self.tableView setContentOffset:CGPointMake(0, y) animated:YES];
//        }];
//    }else{
//    
//        [UIView animateWithDuration:duration animations:^{
//            //        self.inputTextField.frame = inputFieldRect;
//            //        self.moreInputTypeBtn.frame = moreBtnRect;
//            [self.tableView setContentOffset:CGPointMake(0, -y) animated:YES];
//        }];
//    }
    [UIView animateWithDuration:duration animations:^{
        //        self.inputTextField.frame = inputFieldRect;
        //        self.moreInputTypeBtn.frame = moreBtnRect;
//        [self.tableView setContentOffset:CGPointMake(0, -yOffset) animated:YES];
    }];
    
}
- (void)keyBoardShowNotify:(NSNotification *)aNotification
{
//    _gest = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(closeKeyBoard)];
//    [self.tableView addGestureRecognizer:_gest];
    NSDictionary* info = [aNotification userInfo];
    //kbSize为键盘尺寸
    CGSize kbSize = [[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size;
    //键盘高度
  CGFloat  _kH = kbSize.height;
    
    //改变textView的frame
//    self.textView.frame = CGRectMake(0, screenH - _kH - 40, screenW, 40);
    
    //计算偏移量，20是状态栏高度，y其实就是cell底部到textView的y坐标的距离
    NSInteger y = ( _y + 20) - (screenH - (_kH + 40));
    
    //偏移量为正数
    if (y > 0) {
        [self.tableView setContentOffset:CGPointMake(0, y) animated:YES];
    }
}
- (void)cellWillBeginEditingWithModel:(BGAddInviteOneBaseModel *)model
{
    CGRect rect = [self.tableView rectForRowAtIndexPath:model.indexPath];
    GWLog(@"%f",rect.origin.y);
    _y = rect.origin.y;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
//    NSLog(@"%@",indexPath);
    BGAddInviteOneBaseModel *model = _dataArray[indexPath.section][indexPath.row];
    if (model.option) {
        model.option();
    }
    CGRect rect = [self.tableView rectForRowAtIndexPath:indexPath];
    _y = rect.origin.y;
    GWLog(@"%@",NSStringFromCGRect(rect));
}

/**
 *  关闭键盘
 */
- (void)closeKeyBoard
{
    [self.tableView endEditing:YES];
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
#pragma mark - ⬇️ 有数据加载数据
- (void)setGoodsId:(NSString *)goodsId
{
    _goodsId = goodsId;
    [MBProgressHUD showMessage:@"加载中..."];
    [BGDateResult ownInviteDetailsWithInviteId:goodsId success:^(NSObject *result) {
        [MBProgressHUD hideHUD];
        BGGoodInfoDataResult *resultModel = (BGGoodInfoDataResult *)result;
        BGGoodInfoResult *model = resultModel.res;
        cat_id = model.cat_id;
        goodsAttrArray = [NSArray arrayWithArray:model.goods_attrs];
//        BGGoodAttrsModel *modelsss = [goodsAttrArray firstObject];
        [self initDateWithModel:model];
    } failure:^(NSError *error) {
        [MBProgressHUD hideHUD];
        
    }];
    
}

@end
